const course = require('../models/course')
const users = require('../models/users')
const studentWork = require('../models/studentWork')
const teamInvitation = require('../models/teamInvitation')
const teamWork = require('../models/teamWork')
const formidable = require('formidable')
const node_xlsx = require('node-xlsx')
const fs = require('fs')
/****
 *
 * 创建多个班级(excel表)
 *
 */
var Excel_course = async(ctx,next)=>{
    var arr1 =new Array();
    ////////////////////////
    var ExcelParse = async function(newPath,course_Data){
        var arr = new Array();//存放已经创建的班级
        var obj = node_xlsx.parse(newPath);
        var excelObj = obj[0].data;
        //统计学生信息
        var num = 0;
        var courseArray = new Array('course','teacher','student','time','week','place');
        for(var i=1;i<excelObj.length;i++){
            var rdata = excelObj[i];
            if(!rdata[0]){
                continue;
            }
            var courseData={};
            for(var j=0;j<rdata.length;j++){
                if(courseArray[j]=='student'){
                    courseData[courseArray[j]]=rdata[j].split(',');
                    continue;
                }
                courseData[courseArray[j]]=rdata[j];
            }
            //调试
            console.log(courseData);
            //导入数据库
            var document = await course.findOne({course:courseData.course});
            if(document){
                arr.push(userData);
            }else{
                var courseEntity = new course({
                    course:courseData.course,
                    teacher:courseData.teacher,
                    student:courseData.student,
                    time:courseData.time,
                    week:courseData.week,
                    place:courseData.place,
                })
                courseEntity.save(function(err,doc){
                    if(err){
                        console.log(err);
                    }else{
                        console.log(doc);
                    }
                })
            }
        }
        console.log('成功')
        return arr;
    }
    //////////////////////
    var fileParse = async function(){
        var form = new formidable.IncomingForm();
            form.encoding = 'utf-8';
            form.uploadDir = './upload/course/';
            form.keepExtensions = true;
            form.maxFieldsSize = 2*1024*1024;
        return new Promise((resolve,reject)=>{
            form.parse(ctx.req,async function(err,fields,files){
                if(err){
                    console.log(form);
                    console.log("err"+err);
                    return;
                }
                var fileName = files.fileName.name;
                var nameArray = fileName.split('.')
                var type = nameArray[nameArray.length-1];
                var name="";
                for(var i=0;i<nameArray.length-1;i++){
                    name = name+nameArray[i];
                }
                var date = new Date();
                var time = '_'+date.getFullYear()+'_'+(date.getMonth()+1)+'_'+date.getDate()+'_'+date.getHours()+'_'+date.getMinutes()+'_'+date.getSeconds();
                var avatarName = name+time+'.'+type;
                var newPath = form.uploadDir+avatarName;
                console.log(newPath);
                fs.renameSync(files.fileName.path,newPath);
                console.log("重命名成功");
                //////////////////
                var arr = await ExcelParse(newPath,fields);
                resolve(arr);
            })
        })
    }
    ////////////////////
    arr1 = await fileParse();
    console.log(arr1.length)
    if(arr1.length==0){
        ctx.response.body = {stauts:'success',msg:'全部创建成功'};
    }else{
        ctx.response.body = {stauts:'warn',msg:'部分已经创建',arr1};
    }
}
/**
 *
 *
 * 创建一个班级（学生信息EX表）
 *
 */
var creatCourse = async(ctx,next)=>{
    ////////////////////////
    var ExcelParse = async function(newPath,course_Data){
        var obj = node_xlsx.parse(newPath);
        var excelObj = obj[0].data;
        var tea = await users.findOne({userID:course_Data.userID})
        await users.findByIdAndUpdate(tea._id,{$addToSet:{course:course_Data.course}},function(err,res){
            console.log(err);
        })
        var stuData = new Array();
        var unStuData = new Array();
        for(var i=1;i<excelObj.length;i++){
            var rdata = excelObj[i];
            if(!rdata[0]){
                continue;
            }
            var stu = await users.findOne({userID:rdata[0]})
            if(stu){
                await users.findByIdAndUpdate(stu._id,{$addToSet:{course:course_Data.course}},function(err,res){
                    console.log(err);
                })
                stuData.push(rdata[0]);
            }else{
                unStuData.push(rdata[0]);
            }

        }
        var courseEntity = new course({
            course:course_Data.course,
            teacher:course_Data.userID,
            student:stuData,
            time:course_Data.time||"",
            week:course_Data.week||"",
            place:course_Data.place||""
        })
        courseEntity.save(function(err,doc){
            if(err){
                console.log(err);
            }else{
                console.log(doc);
            }
        })
        console.log('成功')
        return unStuData;
    }
    //////////////////////
    var fileParse = async function(){
        var form = new formidable.IncomingForm();
            form.encoding = 'utf-8';
            form.uploadDir = './upload/course/';
            form.keepExtensions = true;
            form.maxFieldsSize = 2*1024*1024;
        return new Promise((resolve,reject)=>{
            form.parse(ctx.req,async function(err,fields,files){
                if(err){
                    console.log(form);
                    console.log("err"+err);
                    return;
                }
                ////避免重复创建班级
                var document = await course.findOne({course:fields.course});
                if(document){
                    resolve("warm")
                }else{
                    var fileName = files.fileName.name;
                    var nameArray = fileName.split('.')
                    var type = nameArray[nameArray.length-1];
                    var name="";
                    for(var i=0;i<nameArray.length-1;i++){
                        name = name+nameArray[i];
                    }
                    var date = new Date();
                    var time = '_'+date.getFullYear()+'_'+(date.getMonth()+1)+'_'+date.getDate()+'_'+date.getHours()+'_'+date.getMinutes()+'_'+date.getSeconds();
                    var avatarName = name+time+'.'+type;
                    var newPath = form.uploadDir+avatarName;
                    console.log(newPath);
                    fs.renameSync(files.fileName.path,newPath);
                    console.log("重命名成功");
                    //////////////////
                    var arr = await ExcelParse(newPath,fields);
                    if(arr.length==0){
                        resolve("success");
                    }else{
                        resolve(arr);
                    }

                }
            })
        })
    }
    ////////////////////
    var arr1 = await fileParse();
    console.log(arr1);
    if(arr1=="success"){
        ctx.response.body = {stauts:'success',msg:'创建成功'};
    }else if(arr1=="warm"){
        ctx.response.body = {stauts:'warn',msg:'班级已经存在'};
    }else{
        ctx.response.body = {stauts:'error',msg:'部分学生不存在',arr1};
    }
}
/**
 *
 *
 * 获取班级信息
 *
 */
var getCourse = async(ctx,next)=>{
    var user = await users.findOne({userID:ctx.request.body.userID});
    var courseArr = user.course.sort();
    var Arr = new Array()
    for(var i=0;i<courseArr.length;i++){
        var oCourse = await course.findOne({course:courseArr[i]})
        Arr.push(oCourse);
    }
    if(user.root==4){
        var work_stu = await studentWork.find({studentID:ctx.request.body.userID,accessory:""}).sort({"endTime":1});
        var work_team = await teamWork.find({teamMember:ctx.request.body.userID})
        var team = new Array()
        for (var i=0;i<work_team.length;i++){
            for(var j=0;j<work_team[i].work.length;j++){
                if(work_team[i].work[j].accessory==""){
                    team.push(work_team[i].work[j])
                }
            }
        }
        var teamInvit = await teamInvitation.find({invitee:ctx.request.body.userID})
        var inviterArr=new Array();
        for(var i=0;i<teamInvit.length;i++){
            var inviter = await users.findOne({userID:teamInvit[i].inviter})
            inviterArr.push(inviter.userName);
        }
        
    }
    ctx.response.body = {stauts:'success',msg:'获取成功',Arr,work_stu,team,teamInvit,inviterArr};
}
/**
 *
 *
 * 获取班级里学生信息
 *
 *
 */
var getStudent = async(ctx,next)=>{
    var oCcourse = await  course.findOne({course:ctx.request.body.course})
    var stuArr = oCcourse.student.sort();
    var Arr = new Array()
    for(var i=0;i<stuArr.length;i++){
      console.log(stuArr[i]);
        var student = await users.findOne({userID:stuArr[i]})
        student.password=null;
        Arr.push(student);
    }
    ctx.response.body = {stauts:'success',msg:'获取成功',Arr};
}

/**
 *
 * 开放团队/关闭团队
 * course
 */
var changeTeam = async(ctx,next)=>{
    var oCcourse = await  course.findOne({course:ctx.request.body.course})
    if(oCcourse.isTeam==false){
        await course.findByIdAndUpdate(oCcourse._id,{$set:{isTeam:true}});
    }else if(oCcourse.isTeam==true){
        await course.findByIdAndUpdate(oCcourse._id,{$set:{isTeam:false}});
    }
    return ctx.response.body = {stauts:'success',msg:'成功'};
}

/**
 *
 * 获取全部班级信息
 *
 */
var getAllCourse = async(ctx,next)=>{
    let allCourse= await course.find();
    return ctx.response.body = {stauts:'success',msg:'成功',allCourse};
}
/**
 *
 * 删除班级信息
 * course
 */
var deleteCourse = async(ctx,next)=>{
    let oCourse= await course.findOne({course:ctx.request.body.course});
    if(oCourse){
        await course.findByIdAndRemove(oCourse._id)
        var userArr = await users.find({course:ctx.request.body.course})
        for(var i=0;i<userArr.length;i++){
            await users.findByIdAndUpdate(userArr[i]._id,{$pull:{course:ctx.request.body.course}})
        }
        return ctx.response.body = {stauts:'success',msg:'成功'};
    }else{
        return ctx.response.body = {stauts:'error',msg:'班级不存在'};
    }
}
/**
 *
 * 班级中添加单个学生
 * userID,course
 */
var pushStudent = async(ctx,next)=>{
    let oCourse= await course.findOne({course:ctx.request.body.course});
    if(oCourse){
        var document = await users.findOne({userID:ctx.request.body.userID})
        if(document){
            for(var i=0;i<oCourse.student.length;i++){
                if(ctx.request.body.userID==oCourse.student[i]){
                    return ctx.response.body = {stauts:'error',msg:'学生已存在班级中'};
                }
            }
            await course.findByIdAndUpdate(oCourse._id,{$addToSet:{student:ctx.request.body.userID}})
            await users.findByIdAndUpdate(document._id,{$addToSet:{course:ctx.request.body.course}})
            return ctx.response.body = {stauts:'success',msg:'成功',document};
        }else{
            return ctx.response.body = {stauts:'error',msg:'学生不存在'};
        }
    }else{
        return ctx.response.body = {stauts:'error',msg:'班级不存在'};
    }
}
/**
 *
 * 班级中删除单个学生
 * userID,course
 */
var pullStudent = async(ctx,next)=>{
    let oCourse= await course.findOne({course:ctx.request.body.course});
    if(oCourse){
        var document = await users.findOne({userID:ctx.request.body.userID})
        if(document){
            await course.findByIdAndUpdate(oCourse._id,{$pull:{student:ctx.request.body.userID}})
            await users.findByIdAndUpdate(document._id,{$pull:{course:ctx.request.body.course}})
            return ctx.response.body = {stauts:'success',msg:'成功'};
        }else{
            return ctx.response.body = {stauts:'error',msg:'学生不存在'};
        }
    }else{
        return ctx.response.body = {stauts:'error',msg:'班级不存在'};
    }
}
module.exports = {
    'POST /course/Excel_course': Excel_course,
    'POST /course/creatCourse': creatCourse,
    'POST /course/getCourse': getCourse,
    'POST /course/getStudent': getStudent,
    'POST /course/changeTeam': changeTeam,
    'POST /course/getAllCourse': getAllCourse,
    'POST /course/deleteCourse': deleteCourse,
    'POST /course/pushStudent': pushStudent,
    'POST /course/pullStudent': pullStudent,
}
